<?php

// 强制使用 UTF-8 编码
if (function_exists('mb_internal_encoding')) {
    mb_internal_encoding('UTF-8');
}
if (function_exists('mb_http_output')) {
    mb_http_output('UTF-8');
}

$host = '127.0.0.1';
$port = 8775;

echo "UTF-8 Telnet Client\n";
echo "===================\n\n";

$socket = fsockopen($host, $port, $errno, $errstr, 10);

if (!$socket) {
    die("Connection failed: {$errstr} ({$errno})\n");
}

// 读取欢迎信息
stream_set_blocking($socket, false);
$start = time();
while ((time() - $start) < 2) {
    $data = fread($socket, 1024);
    if ($data) {
        // 检测并转换编码
        if (function_exists('mb_detect_encoding')) {
            $encoding = mb_detect_encoding($data, ['UTF-8', 'GBK', 'ASCII'], true);
            if ($encoding && $encoding !== 'UTF-8') {
                $data = mb_convert_encoding($data, 'UTF-8', $encoding);
            }
        }
        echo $data;
    }
    usleep(100000);
}

$commands = [
    "help",
    "mul 3 4", 
    "incr 10",
    "div 9 4",
    "conv_tree",
    "exit"
];

foreach ($commands as $command) {
    echo "\n>>> {$command}\n";
    fwrite($socket, $command . "\n");
    
    $response = '';
    $start = time();
    while ((time() - $start) < 2) {
        $data = fread($socket, 1024);
        if ($data) {
            // 检测并转换编码
            if (function_exists('mb_detect_encoding')) {
                $encoding = mb_detect_encoding($data, ['UTF-8', 'GBK', 'ASCII'], true);
                if ($encoding && $encoding !== 'UTF-8') {
                    $data = mb_convert_encoding($data, 'UTF-8', $encoding);
                }
            }
            $response .= $data;
        }
        usleep(100000);
    }
    
    echo trim($response) . "\n";
    sleep(1);
}

fclose($socket);